package cn.seaboot.plugin.redis;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Redis 使用 FastJson 序列化数据，满足所有数据类型的序列化
 *
 * @author Mr.css
 * @version 2020-01-02 11:24
 */
public class FastJsonRedisSerializer implements RedisSerializer<Object> {

    /**
     * 包含各类序列化配置
     */
    private final JSONWriter.Feature[] features;
    /**
     * 反序列化拦截器
     */
    private final JSONReader.AutoTypeBeforeHandler filter;


    /**
     * 默认序列化的时候，写入全类名
     *
     * @param names 允许自动转型的包
     */
    public FastJsonRedisSerializer(String... names) {
        this.features = new JSONWriter.Feature[]{JSONWriter.Feature.WriteClassName};
        this.filter = JSONReader.autoTypeFilter(names);
    }

    /**
     * 序列化
     *
     * @param obj 对象实体
     * @return 字节数组
     * @throws SerializationException -
     */
    @Override
    public byte[] serialize(Object obj) throws SerializationException {
        if (obj == null) {
            return new byte[0];
        } else {
            return JSON.toJSONBytes(obj, features);
        }
    }

    /**
     * 反序列化
     *
     * 不在白名单的对象，不会反序列化失败，而是返回 com.alibaba.fastjson2.JSONObject，
     *
     * @param bytes 字节数组
     * @return 对象实体
     * @throws SerializationException -
     */
    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        } else {
            return JSON.parseObject(bytes, Object.class, filter);
        }
    }
}